<template>
	<view class="cf_container">
		<view class="" v-if="tab_list">
			<view class="post" :style="'top:0rpx;'" style="z-index: 100;">
				<ul class="df ac bgcf bbf1">
					<block v-for="(item, index) in tab_list" :key="index">
						<li class="df ac jc h44 w50" @tap.native="ontabShow(index)" :data-i="index" style="width: 250rpx;">
							<P :class="'f14 ' + (item.show ? 'c10' : 'c6b')" class="tabListName">{{ item.name }}</P>
							<image class="down ml8" referrerPolicy='no-referrer'
								:src="item.show ? 'https://wx.xtwaixie.com/img/down1.png' : 'https://wx.xtwaixie.com/img/down.png'" />
						</li>
					</block>
				</ul>
			</view>
		</view>
		<view class="list" v-if="list.length !== 0">
			<FactoryInfo :highlight_first="false" :list="list" :mb="20"/>
		</view>
		<view class="df jc mt30" v-else style="flex-direction: column;align-items: center;">
			<image src="https://wx.xtwaixie.com/img/empty.png" style="width: 250rpx;" mode="widthFix"></image>
			<view class=""
				style="font-weight: bold;font-size: 32rpx;margin-top: 50rpx;margin-bottom:20rpx;color: #6b758c;">
				暂无收藏的工厂
			</view>
		</view>
		
		<van-popup :show="tab_list[0].show"  @close="closePopup" round position="bottom">
			<van-datetime-picker type="date" :value="currentDate" :min-date="minDate" :max-date="maxDate" @confirm='input($event,0)'
				@cancel='cancel' title='开始时间' />
		</van-popup>
		<van-popup :show="showsecondTime" @close="closePopup" round position="bottom">
			<van-datetime-picker type="date" :value="currentDates" :min-date="minDates" :max-date="maxDate" @confirm='input($event,1)'
				@cancel='cancel' title='截止时间' />
		</van-popup>
		<van-popup :show="screen_popup" @close="closePopup" position="top">
			<view class="" :style="'padding-top:' + (navTop * 2 + 90) + 'rpx;'">
				<ul class="df ac bgcf bbf1">
					<block v-for="(item, index) in tab_list" :key="index">
						<li class="df ac jc h44 w50" @tap.native="ontabSel($event, { i: index })" :data-i="index"
							style="width: 250rpx;">
							<P :class="'f14 ' + (item.show ? 'c10' : 'c6b')" class="tabListName">{{ item.name }}</P>
							<image class="down ml8" referrerPolicy='no-referrer'
								:src="item.show ? 'https://wx.xtwaixie.com/img/down1.png' : 'https://wx.xtwaixie.com/img/down.png'" />
						</li>
					</block>
				</ul>
				<view class="" style="display: flex;" v-if="tab_list[0].show">
					<view class="position_screen">
						<view class="mt10">
							当前位置
						</view>
						<view class="position_list df mt20">
							<view :class="screen_index[0] == index ? 'position_item_active position_item' : 'position_item'"
								:style="index == 0 ? '' : 'line-height:65rpx'" @click="changeScreen(0,index)"
								v-for="(item,index) in position_screen" :key="index">
								<view class="">
									{{ item == 0 ? '附近' : item + '公里' }}
								</view>
								<view class="f12" v-if="item == 0" :style=" screen_index[0] == index ? 'color:#4874CB;' : 'color:gray'">
									智能范围
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="h360" style="display: flex;" v-if="tab_list[1].show">
					<scroll-view class="h360 bgcf7" :scroll-y="true" style="width: 250rpx;">
						<ul class="db">
							<block v-for="(item, index) in info.machiningre" :key="index">
								<li class="pd015 h48 df ac sb" :class="{bgcf:screen_index[1] == index}"
									@tap.native="changeTab(index,item.id,item.name)">
									<p :class="'f14 c28 ' + (screen_index[1] == index ? 'c10' : '')">{{ item.name }}
									</p>
								</li>
							</block>
						</ul>
					</scroll-view>
				</view>
				<view class="df" v-if="tab_list[2].show">
					<scroll-view class="h360 w125 bgcf7" :scroll-y="true">
						<ul class="db">
							<block v-for="(item, index) in province_list" :key="index">
								<li :class="'tab-left ' + (region[0].act === item.region_id ? 'bgcf' : '')"
									@tap.native="onRegion($event, { name: item.region_name, id: item.region_id, type: 0 })"
									:data-name="item.region_name" :data-id="item.region_id" :data-type="0">
									<p :class="'f14 c28 ovh w110 ' + (region[0].act === item.region_id ? 'c10' : '')">
										{{ item.region_name }}
									</p>
								</li>
							</block>
						</ul>
					</scroll-view>
					<scroll-view class="h360 f1" :scroll-y="true">
						<ul class="db">
							<block v-for="(item, index) in city_list" :key="index">
								<li class="pd015 h48 df ac sb"
									@tap.native="onRegion($event, { name: item.region_name, id: item.region_id, type: 1 })"
									:data-name="item.region_name" :data-id="item.region_id" :data-type="1">
									<p :class="'f14 c28 ' + (region[1].act === item.region_id ? 'c10' : '')">
										{{ item.region_name }}
									</p>
									<image class="sel" src="https://wx.xtwaixie.com/img/sel.png" v-if="region[1].act === item.region_id" />
								</li>
							</block>
						</ul>
					</scroll-view>
				</view>
			</view>
		</van-popup>
	</view>
</template>

<script>
	import http from '../../utils/http';
	import FactoryInfo from '@/component/factory'
	export default {
		components: {
			FactoryInfo
		},
		data() {
			return {
				minDate: new Date(2020, 0, 1).getTime(),
				maxDate: new Date().getTime(),
				currentDate: new Date().getTime(),
				currentDates: '',
				tab_list: [{
						show: false,
						name: '日期',
						act: ''
					},
					{
						show: false,
						name: '工艺',
						act: ''
					},
					{
						show: false,
						name: '地区',
						act: '',
					}
				],
				region: [{
					name: '',
					act: ''
				}, {
					name: '',
					act: ''
				}, {
					name: '',
					act: ''
				}],
				screen_popup:false,
				position_screen: [0, 5, 20, 50, 100],
				screen_index: [-1, 0, -1],
				info: [],
				province_list: [],
				city_list: [],
				list:[],
				page:1,
				showsecondTime:false,
				start_date:'',
				end_date:'',
				lat:0,
				long:0,
				pageTotal:1
			};
		},
		onLoad() {
			// console.log(Math.ceil(33/10))
			this.getBase()
		},
		onReachBottom() {
			if(this.pageTotal > this.page){
				this.page++
				this.getList();
			} else {
				uni.showToast({
					title: '没有更多了~',
					icon: 'none'
				});
			}
		},
		onShow() {
			this.getRegion(1)
			this.lat = uni.getStorageSync('latitude')
			this.long = uni.getStorageSync('longitude')
			if(this.lat && this.long){
				this.getList(this.lat,this.long)
			} else {
				const that = this
				uni.getLocation({
					isHighAccuracy: true,
					type: 'gcj02',
					success(res) {
						that.lat = res.latitude
						that.long = res.longitude
						that.getList(res.latitude,res.longitude)
					},
					err(err) {
						console.log(err)
					}
				})
			}
		},
		methods:{
			getList(lat,long){
				// this.tab_list[1].act
				const data = {
					type:4,
					page:this.page,
					pageSize:10,
					latitude:lat ? lat : this.lat,
					longitude:long ? long : this.long,
					province:this.region[0].name == '全部' ? '' : this.region[0].name,
					city:this.region[1].name == '全部' ? '' : this.region[1].name,
					start_date:this.start_date,
					end_date:this.end_date,
					machining:this.tab_list[1].act
				}
				http.request('user/collectList',data).then(res=>{
					console.log(res)
					if(this.page == 1){
						this.list = res.data.list.map(item=>{
							item.UserSettledInfo.machining = item.UserSettledInfo.machining.join('、')
							item.UserSettledInfo.service_industry = item.UserSettledInfo.service_industry.join('、')
							const data = {
								...item.UserSettledInfo,
								...item,
								my_uid:item.uid,
								userSettledInfo:{
									main_products:[]
								},
								...item.relation_data,
								created_at:item.created_at
							}
							return data
						})
					} else {
						res.data.list.forEach(item=>{
							item.UserSettledInfo.machining = item.UserSettledInfo.machining.join('、')
							item.UserSettledInfo.service_industry = item.UserSettledInfo.service_industry.join('、')
							const data = {
								...item.UserSettledInfo,
								...item,
								my_uid:item.uid,
								userSettledInfo:{
									main_products:[]
								},
								...item.relation_data,
								created_at:item.created_at
							}
							this.list.push(data)
						})
					}
					this.list.forEach(item => {
						if (!item.unit) {
							item.unit = "公里"
							// 超过一百公里
							if (item.distance_in_km >= 100) {
								item.distance_in_km = parseInt(item.distance_in_km)
							} else if (item.distance_in_km >= 1 && item.distance_in_km < 100) {
								// 大于一公里小于100公里
								item.distance_in_km = (item.distance_in_km).toFixed(1)
							} else {
								item.distance_in_km = parseInt(item.distance_in_km * 1000)
								item.unit = "米"
							}
						}
					})
					 this.pageTotal = this.calculateTotalPages(res.data.total,10)
					 // console.log(this.list)
				})
			},
			calculateTotalPages(total,itemsPerPage){
				return Math.ceil(total / itemsPerPage);
			},
			getRegion(id) {
				const data = {
					pid: id
				};
				http.request('base/region', data).then((res) => {
					if (id === 1) {
						this.setData({
							province_list: res.data
						});
					} else {
						this.setData({
							city_list: res.data
						});
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			},
			getBase() {
				http.request('base/configData').then((res) => {
					const machiningData = res.data.machining || [];
					res.data.machiningre = [{
						id: 0,
						name: '全部',
						children: []
					}, ...machiningData];
					res.data.machiningre.forEach(item => {
						item.children.unshift({
							name: "全部",
							id: item.id,
							machining_type: 0
						});
					});
					this.info = res.data
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			},
			cancel() {
				// this.show = false
				// this.showsecondTime = false
				this.setData({
					[`tab_list[0].show`]: false,
					showsecondTime:false
				});
			},
			input(e, i) {
				var date = new Date(e.detail); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = date.getDate();
				if (i === 0) {
					this.currentDates = e.detail
					this.minDates = e.detail
					this.start_date = Y + M + D
					this.setData({
						[`tab_list[0].show`]: false,
					});
					this.showsecondTime = true
				} else {
					this.end_date = Y + M + D
					this.showsecondTime = false
					// this.date = `${this.firstTime} - ${this.secondTime}`
					this.setData({
						act: i,
						[`tab_list[0].name`]: `${this.start_date} - ${this.end_date}`,
						list:[]
					});
					this.page = 1
					this.getList()
				}
			},
			ontabShow(index) {
				if(index === 0){
					this.setData({
						[`tab_list[0].show`]:true
					})
					return
				}
				this.screen_popup = true
				this.tab_list.forEach((item, i) => {
					item.act = (index === i) ? i : '';
					item.show = (index === i);
				});
			},
			closePopup() {
				this.screen_popup = false
				this.tab_list.forEach((item, i) => {
					// item.act = '';
					item.show = false;
				});
				this.showsecondTime = false
			},
			ontabSel(e, _dataset) {
				/* ---处理dataset begin--- */
				// this.handleDataset(e, _dataset);
				/* ---处理dataset end--- */
				let index = e.currentTarget.dataset.i;
			
				this.tab_list.forEach((item, i) => {
					item.act = (index === i) ? i : '';
					item.show = (index === i);
				});
			},
			onRegion(e, _dataset) {
				let name = e.currentTarget.dataset.name;
				let id = e.currentTarget.dataset.id;
				let type = e.currentTarget.dataset.type;
				this.setData({
					[`region[${type}].name`]: name,
					[`region[${type}].act`]: id
				});
				if (type == 0) {
					this.getRegion(id);
				} else if (type == 1) {
					this.setData({
						page: 1,
						list: [],
						[`tab_list[2].name`]: name === '全部' ? '地区' : name
					});
					this.getList();
					setTimeout(() => {
						this.closePopup()
					}, 20)
					// this.onClose();
				}
			},
			changeTab(index, id, name) {
				// this.onTab(id,name)
				// let act = this.act;
				// console.log(name, id);
				let status = false
				this.setData({
					[`screen_index[1]`]: index,
					[`tab_list[${1}].name`]: name == '全部' ? '工艺' : name,
					[`tab_list[${1}].act`]: id,
					// [`tab_list[${1}].show`]:status,
					// screen_popup:status
					list: [],
					page: 1
				});
				setTimeout(() => {
					this.closePopup()
				}, 50)
				// console.log(id)
				this.getList();
				// this.onClose();
			},
			changeScreen(i, index) {
				if (this.screen_index[i] === index) {
					this.$set(this.screen_index, i, -1);
				} else {
					this.$set(this.screen_index, i, index);
				}
				const name = this.position_screen[index]
				this.setData({
					[`tab_list[${i}].show`]: false,
					[`tab_list[${i}].name`]: name === 0 ? '附近' : name + '公里',
					[`tab_list[${i}].act`]: name
				})
				this.screen_popup = false
				// this.selectComponent('#item').toggle();  
			},
			goPage(path,id){
				uni.navigateTo({
					url: id ? `${path}?id=${id}` : path
				})
			}
		}
	}
</script>

<style lang="scss">
	.list{
		padding:30rpx;
		box-sizing:border-box;
	}
	page{
		background-color: #F7F8FC;
	}
.cf_container{
	
.factory_box {
	background-color: #FFF;
	padding: 20rpx 20rpx 30rpx 20rpx;
	position: relative;
	border-radius:20rpx;
}
.factory_box_after{
	&::after{
		position: absolute;
		content:'';
		bottom:10rpx;
		left:50%;
		height:1px;
		background:rgba(0,0,0,0.2);
		width:calc(100% - 40rpx);
		transform: translate(-50%, 0%);
		z-index:9;
	}
}

.factory_year {
	width: 100%;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 99;
	font-size: 22rpx;
	text-align: center;
}

.factory_img {
	width: 30%;
	height: 290rpx;
	position: relative;
}

.factory_img image {
	width: 100%;
	height: 100%;
	border-radius: 15rpx;
}

.factory_content {
	width: 68%;
	height: 290rpx;
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	justify-content: flex-start;
}

.factory_content_name {
	width: 85rpx;
	color: gray;
}

.factory_content_text {
	flex:1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.factory_img_item {
	width: 160rpx;
	height: calc(160rpx * 0.66);
	/* height: 120rpx; */
}

.factory_img_item image {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
}
}
.tabListName {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	.position_screen {
		padding: 20rpx 20rpx 40rpx;
	}
	
	.position_list {
		flex-wrap: wrap;
	}
	
	.position_item {
		height: 65rpx;
		padding: 5rpx 20rpx;
		border-radius: 35rpx;
		/* line-height:65rpx; */
		text-align: center;
		background: #F5F6F5;
		font-size: 26rpx;
		/* box-sizing:border-box; */
		color: #000;
		margin-right: 15rpx;
	}
	
	.position_item_active {
		background: #BCC9EC !important;
		color: #4874CB !important;
	}
	
	.tab-left {
		padding-left: 40rpx;
		line-height: 96rpx;
		font-size: 28rpx;
		color: #6b758c;
		display: block;
	}
</style>
